package controller;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.zt.sso.util.SsoCheck;
import com.zt.sso.util.SsoRedisManager;

import service.UserService;
import vo.UserInfoVO;

@Controller
@RequestMapping("/userInfo")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping("getUserFormMaster")
	public Object getUserInfofromMaster(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<UserInfoVO> users = userService.getUserInfofromMaster();
		System.out.println(JSON.toJSON(users));
		//request.getRequestDispatcher("/login.jsp").forward(request, response);
		return "/index/index";
	}
	@RequestMapping("/getUserInfoFromSlave")
	@ResponseBody
	public Object getUserInfoFromSlave() {
		List<UserInfoVO> users = userService.getUserInfoFromSlave();
		System.out.println(JSON.toJSON(users));
		return JSON.toJSON(users);
	}
	
	@RequestMapping("/loginIn")
	public Object loginIn(HttpServletRequest request, HttpServletResponse response, String name, String pass) {
		if(StringUtils.isNotEmpty(name)&&StringUtils.isNotEmpty(pass)){
			if("admin".equals(name) && "123456".equals(pass)){
				SsoCheck.setCookie(response, "userId", name, 3600);
				 int index = (int) (System.currentTimeMillis() % 13);
			     String token =  UUID.randomUUID().toString().replaceAll("-", "").substring(index, index + 16);
			     SsoCheck.setCookie(response, "token", token, 3600);
			     SsoCheck.setCookie(response, "userType", "admin", 3600);
			     SsoRedisManager.setSsoRedisByMs(token, "admin$"+name, 3600);
			}
		}
		return "/index/index";
	}
	
	@RequestMapping("/login")
	public Object login(HttpServletRequest request) {		
		return "login/login";
	}
}
